package pers.zh.parking.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import per.goweii.anylayer.AnyLayer;
import per.goweii.anylayer.Layer;
import pers.zh.parking.common.Const;
import pers.zh.parking.data.entity.Notice;
import pers.zh.parking.data.entity.ParkingLot;
import pers.zh.parking.data.entity.ParkingSpace;
import pers.zh.parking.di.component.DaggerSpaceComponent;
import pers.zh.parking.mvp.contract.SpaceContract;
import pers.zh.parking.mvp.presenter.SpacePresenter;

import pers.zh.parking.R;
import pers.zh.parking.mvp.ui.adapter.SpaceAdapter;
import pers.zh.parking.mvp.ui.adapter.StatusAdapter;
import pers.zh.parking.utils.UIUtils;
import pers.zjc.commonlibs.util.ToastUtils;
import pers.zjc.commonlibs.util.VibrateUtils;

import static com.jess.arms.utils.Preconditions.checkNotNull;

public class SpaceActivity extends BaseActivity<SpacePresenter> implements SpaceContract.View {

    private static final int TYPE_EDIT = 1;
    private static final int TYPE_ADD = 2;

    private String[] statusList = {"空闲", "在用", "预约中"};

    @BindView(R.id.ivLeft)
    ImageView ivLeft;
    @BindView(R.id.toolbar_left)
    RelativeLayout toolbarLeft;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.rl)
    SmartRefreshLayout rl;

    private Layer layer;

    private SpaceAdapter mAdapter;

    private List<ParkingSpace> toDels = new ArrayList<>();
    private String formatTitle = "已选择%s项";

    private boolean delModel; // 右上角图标控制变量,是否处于删除模式，默认为否
    private ParkingLot lot;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerSpaceComponent //如找不到该类,请编译一下项目
                                    .builder()
                                    .appComponent(appComponent)
                                    .view(this)
                                    .build()
                                    .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_reservation; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initArgs();
        initView();
        mPresenter.loadData(lot.getLotId());
    }

    private void initArgs() {
        Intent intent = getIntent();
        if (null == intent) {
            showMessage("参数错误");
            killMyself();
            return;
        }
        lot = intent.getParcelableExtra(Const.Keys.KEY_PARKING_LOT);
        if (lot == null) {
            showMessage("参数错误");
            return;
        }
    }

    private void initView() {
        tvTitle.setText("车位管理");
        ivRight.setImageDrawable(getDrawable(R.drawable.ic_add_24dp));
        mAdapter = new SpaceAdapter(new ArrayList<>(), lot);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            ParkingSpace item = mAdapter.getData().get(position);
            if (delModel) {
                // 删除模式下单击改背景
                if (item.isToDel()) {
                    toDels.remove(item);
                }
                else {
                    toDels.add(item);
                }
                item.setToDel(!item.isToDel());
                if (toDels.size() == 0) {
                    if (mAdapter.getData().isEmpty()) {
                        return;
                    }
                    for (ParkingSpace notice : mAdapter.getData()) {
                        notice.setToDel(false);
                    }
                    updateToolBar();
                    mAdapter.notifyDataSetChanged();
                }
                else {
                    tvTitle.setText(String.format(this.formatTitle, toDels.size()));
                    mAdapter.notifyItemChanged(position);
                }
            }
            else {
                // 编辑操作
                showDialog(TYPE_EDIT, item);
            }
        });
        mAdapter.setOnItemLongClickListener((adapter, view, position) -> {
            if (!delModel) {
                VibrateUtils.vibrate(100L);
                // 开启删除模式
                ParkingSpace space = mAdapter.getData().get(position);
                space.setToDel(true);
                toDels.add(space);
                mAdapter.notifyItemChanged(position);
                updateToolBar();
            }
            return true;
        });
        ivLeft.setOnClickListener(v -> {
            if (!delModel) {
                finish();
            }
            else {
                // 删除模式下，清空待删除列表
                toDels.clear();
                if (mAdapter.getData().isEmpty()) {
                    return;
                }
                for (ParkingSpace space : mAdapter.getData()) {
                    space.setToDel(false);
                }
                // 点击叉叉关闭删除模式
                updateToolBar();
                mAdapter.notifyDataSetChanged();
            }

        });
        ivRight.setOnClickListener(v -> {
            if (delModel) {
                delete();
            } else {
                mPresenter.add(lot);
            }

        });
        rl.setOnRefreshListener(refreshLayout -> mPresenter.loadData(lot.getLotId()));
    }

    private void delete() {
        UIUtils.createConfirmDialog(SpaceActivity.this,
                String.format("是否要删除%s项数据?", toDels.size()), true, (dialog, which) -> {
                    mPresenter.delete(toDels);
                }, (dialog, which) -> {}).show();
    }

    private void showDialog(int type, ParkingSpace item) {
        if (type == TYPE_EDIT) {
            if (item == null) {
                showMessage("参数错误");
                return;
            }
        }
        layer = AnyLayer.dialog(this)
                        .contentView(R.layout.popup_edit_space)
                        .backgroundColorRes(R.color.white)
                        .gravity(Gravity.CENTER)
                        .cancelableOnTouchOutside(true)
                        .cancelableOnClickKeyBack(true)
                        .backgroundDimAmount(0.5f)
                        .bindData(layer -> {
                            TextView tvTitle = layer.getView(R.id.tvTitle);
                            tvTitle.setText("设置车位状态");
                            RecyclerView rv = layer.getView(R.id.recyclerView);
                            rv.setLayoutManager(new LinearLayoutManager(SpaceActivity.this));
                            rv.addItemDecoration(new DividerItemDecoration(SpaceActivity.this, DividerItemDecoration.VERTICAL));
                            StatusAdapter adapter = new StatusAdapter(
                                    Arrays.asList(statusList));
                            rv.setAdapter(adapter);
                            adapter.setOnItemClickListener((adapter1, view, position) -> {
                                int status = position + 1;
                                item.setStatus(String.valueOf(status));
                                mPresenter.update(item);
                            });
                        });
        layer.show();
    }

    @Override
    public void showLoading() {
        rl.autoRefresh();
    }

    @Override
    public void hideLoading() {
        rl.finishRefresh();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ToastUtils.showShort(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void updateSuccess() {
        if (layer != null && layer.isShow()) {
            layer.dismiss();
        }
        mPresenter.loadData(lot.getLotId());
    }

    @Override
    public void showData(List<ParkingSpace> list) {
        mAdapter.replaceData(list);
    }

    @Override
    public void deleteSuccess(List<ParkingSpace> list) {
        // UI删除
        Iterator<ParkingSpace> it = mAdapter.getData().iterator();
        while (it.hasNext()) {
            ParkingSpace space = it.next();
            if (list.contains(space)) {
                it.remove();
            }
            mAdapter.notifyDataSetChanged();
        }
        toDels.clear();
        updateToolBar();
        showMessage("删除成功");
    }

    private void updateToolBar() {
        delModel = !delModel;
        ivLeft.setImageDrawable(
                !delModel ? getDrawable(R.drawable.ic_arrow_back_white_24dp) : getDrawable(
                        R.drawable.ic_close_black_24dp));
        ivRight.setImageDrawable(!delModel ? getDrawable(R.drawable.ic_add_24dp) : getDrawable(
                R.drawable.ic_delete_24dp));
        tvTitle.setText(delModel ? String.format(this.formatTitle, toDels.size()) : "通知管理");
    }
}
